package com.github.ghsea.dbtracer.db;

import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.github.ghsea.dbtracer.Bootstrap;
import com.github.ghsea.dbtracer.xml.TableConfiguration;
import com.github.ghsea.dbtracer.xml.TableField;
import com.github.ghsea.dbtracer.xml.XmlDbTraceConfigException;

public class DbHistoryLogUtil {

	public static String createChangeLog(DbHistoryLog history) {
		String tblName = history.getTable();
		Map<String, TableConfiguration> config = Bootstrap.getTableConfiguration();
		TableConfiguration tblConfig = config.get(tblName);
		if (null == tblConfig) {
			String tblNotConfigedMsg = String.format("the table named '%s' has not been configed in the file '%s' ",
					tblName, Bootstrap.getTableConfigFile());
			throw new XmlDbTraceConfigException(tblNotConfigedMsg);
		}

		Map<String, TableField> filedName2Config = tblConfig.getFiledName2Config();
		Map<String, Object> originalCol2Val = history.getOriginalCol2Val();
		Map<String, String> newCol2Val = history.getNewCol2Val();
		Set<Entry<String, Object>> originalEntrySet = originalCol2Val.entrySet();
		StringBuffer changeLog = new StringBuffer();
		int idx = 0;
		int maxIdx = originalEntrySet.size() - 1;
		for (Entry<String, Object> entry : originalEntrySet) {
			String nameEn = entry.getKey();
			TableField field = filedName2Config.get(nameEn);
			String nameCn = field.getNameCn();
			changeLog.append(nameCn).append(":");

			Object originalVal = entry.getValue();
			changeLog.append("{").append(getDescriptionByValue(field, originalVal.toString())).append("}--->{");
			String newVal = newCol2Val.get(nameEn);
			changeLog.append(getDescriptionByValue(field, newVal));
			changeLog.append("}");
			if (idx < maxIdx) {
				changeLog.append(",");
			}
			idx++;

		}

		return changeLog.toString();
	}

	private static String getDescriptionByValue(TableField field, String value) {
		String description = field.getValue2Description().get(value);
		if (description != null) {
			return description;
		}

		return value;
	}

}
